<template>
  <div v-if="hasScene" id="cesiumContainer" class="cesium-container"></div>
  <div v-else class="home-page">暂无场景</div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick, provide } from 'vue'
import { useRoute } from 'vue-router'
import * as Cesium from 'cesium'
import 'cesium/Build/Cesium/Widgets/widgets.css'



const hasScene = ref(!!localStorage.getItem('currentScene'))
  const sceneConfig = ref({
    longitude: 116.4,
    latitude: 39.9,
    height: 15000000,
    startTime: Cesium.JulianDate.now(),
    endTime: Cesium.JulianDate.addHours(Cesium.JulianDate.now(), 24, new Cesium.JulianDate()),
    timeStep: 100
  })
let viewer = null

// 检查场景状态
  const checkScene = () => {
  const sceneData = localStorage.getItem('currentScene')
  hasScene.value = !!sceneData
  if (sceneData) {
    const savedConfig = JSON.parse(sceneData)
    sceneConfig.value = {
      longitude: savedConfig.initialViewpoint?.position?.cartographicDegrees?.[0] || 116.4,
      latitude: savedConfig.initialViewpoint?.position?.cartographicDegrees?.[1] || 39.9,
      height: savedConfig.initialViewpoint?.position?.cartographicDegrees?.[2] || 15000000,
      startTime: savedConfig.timeConfig?.startTime 
        ? Cesium.JulianDate.fromDate(new Date(savedConfig.timeConfig.startTime))
        : Cesium.JulianDate.now(),
      endTime: savedConfig.timeConfig?.endTime 
        ? Cesium.JulianDate.fromDate(new Date(savedConfig.timeConfig.endTime))
        : Cesium.JulianDate.addHours(Cesium.JulianDate.now(), 24, new Cesium.JulianDate()),
      timeStep: savedConfig.timeConfig?.timeStep || 100
    }
  }
}

// 初始化时检查
checkScene()

const loadSatellite = async (sat) => {
  console.log('加载卫星:', sat)
  
  // 创建卫星实体
  const entity = viewer.entities.add({
    name: sat.name,
    position: Cesium.Cartesian3.fromDegrees(116.4, 39.9, 1000000),
    point: {
      pixelSize: 10,
      color: Cesium.Color.RED,
      outlineColor: Cesium.Color.WHITE,
      outlineWidth: 2
    },
    label: {
      text: sat.name,
      font: '14pt sans-serif',
      style: Cesium.LabelStyle.FILL_AND_OUTLINE,
      outlineWidth: 2,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      pixelOffset: new Cesium.Cartesian2(0, -10)
    }
  })

  // 打印轨道数据用于调试
  console.log('轨道数据:', sat.orbit)

  // 检查轨道数据格式
  if (sat.orbit && sat.orbit.startsWith('{')) {
    // JSON格式轨道数据
    try {
      const orbitData = JSON.parse(sat.orbit)
      console.log('JSON轨道数据:', orbitData)
      
      // 创建固定位置或使用提供的轨道参数
      const position = Cesium.Cartesian3.fromDegrees(
        orbitData.longitude || 116.4,
        orbitData.latitude || 39.9,
        orbitData.height || 1000000
      )
      entity.position = position
      
      // 如果有轨道参数，可以计算更精确的位置
      if (orbitData.semiMajorAxis) {
        // 这里可以添加更复杂的轨道计算逻辑
        const satelliteOrbit = new Cesium.SampledPositionProperty()
        // 简单示例：计算圆形轨道
        for (let i = 0; i <= 24 * 4; i++) {
          const time = Cesium.JulianDate.addHours(
            Cesium.JulianDate.now(), 
            i/4, 
            new Cesium.JulianDate()
          )
          const angle = (i/4) * Math.PI / 12
          const x = orbitData.semiMajorAxis * Math.cos(angle)
          const y = orbitData.semiMajorAxis * Math.sin(angle)
          const pos = new Cesium.Cartesian3(x, y, 0)
          satelliteOrbit.addSample(time, pos)
        }
        entity.position = satelliteOrbit
      }
      
      entity.path = {
        resolution: 1,
        material: new Cesium.PolylineGlowMaterialProperty({
          glowPower: 0.1,
          color: Cesium.Color.BLUE
        }),
        width: 2
      }
    } catch (e) {
      console.error('JSON轨道解析错误:', e)
    }
  } else if (sat.orbit && sat.orbit.includes('1 ') && sat.orbit.includes('2 ')) {
    // TLE格式轨道数据
    try {
      console.log('原始TLE数据:', sat.orbit)
      const tleLines = sat.orbit.trim().split('\n')
      if (tleLines.length < 2) {
        console.error('TLE数据行数不足:', tleLines)
        throw new Error('TLE数据格式不正确')
      }
      
      const satelliteTle = new Cesium.SampledPositionProperty()
      const { twoline2satrec, propagate, gstime, eciToGeodetic } = await import('satellite.js')
      const satrec = twoline2satrec(tleLines[0].trim(), tleLines[1].trim())
      console.log('TLE解析结果:', satrec)
      
      // 计算未来24小时的轨道位置 (每15分钟一个点)
      // 使用场景配置的时间范围
      const startTime = sceneConfig.value.startTime
      const endTime = sceneConfig.value.endTime
      const stepHours = Cesium.JulianDate.secondsDifference(endTime, startTime) / (24 * 4 * 3600)
      
      for (let i = 0; i <= 24 * 4; i++) {
        const time = Cesium.JulianDate.addHours(startTime, i * stepHours, new Cesium.JulianDate())
        const date = Cesium.JulianDate.toDate(time)
        const positionAndVelocity = propagate(satrec, date)
        
        if (positionAndVelocity.position) {
          const gmst = gstime(date)
          const positionGd = eciToGeodetic(positionAndVelocity.position, gmst)
          const lon = Cesium.Math.toDegrees(positionGd.longitude)
          const lat = Cesium.Math.toDegrees(positionGd.latitude)
          const height = positionGd.height * 1000
          // console.log(`时间: ${date.toISOString()}, 经度: ${lon}, 纬度: ${lat}, 高度: ${height}`)
          
          const position = Cesium.Cartesian3.fromDegrees(lon, lat, height)
          satelliteTle.addSample(time, position)
        }
      }
      
      entity.position = satelliteTle
      entity.path = {
        resolution: 1,
        material: new Cesium.PolylineGlowMaterialProperty({
          glowPower: 0.1,
          color: Cesium.Color.YELLOW
        }),
        width: 2
      }
    } catch (e) {
      console.error('轨道计算错误:', e)
      viewer.entities.remove(entity)
    }
  }
  return entity
}

const loadSatellites = async () => {
  const satellites = JSON.parse(localStorage.getItem('satellites') || '[]')
  const loadingPromises = []
  
  for (const sat of satellites) {
    loadingPromises.push(loadSatellite(sat))
  }
  
  await Promise.all(loadingPromises)
}

const loadPointTargets = async () => {
  const pointTargets = JSON.parse(localStorage.getItem('pointTargets') || '[]')
  
  for (const target of pointTargets) {
    viewer.entities.add({
      name: target.name,
      position: Cesium.Cartesian3.fromDegrees(
        target.longitude,
        target.latitude,
        target.height
      ),
      point: {
        pixelSize: 12,
        color: Cesium.Color.ORANGE,
        outlineColor: Cesium.Color.WHITE,
        outlineWidth: 2
      },
      label: {
        text: target.name,
        font: '14pt sans-serif',
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        outlineWidth: 2,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        pixelOffset: new Cesium.Cartesian2(0, -15)
      },
      description: target.description
    })
  }
}

const loadAreaTargets = async () => {
  const areaTargets = JSON.parse(localStorage.getItem('areaTargets') || '[]')
  
  for (const target of areaTargets) {
    if (target.points && target.points.length >= 3) {
      const positions = target.points.map(p => 
        Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude)
      )
      
      viewer.entities.add({
        name: target.name,
        polygon: {
          hierarchy: new Cesium.PolygonHierarchy(positions),
          material: Cesium.Color.fromCssColorString(target.color || '#FF0000').withAlpha(0.5),
          outline: true,
          outlineColor: Cesium.Color.WHITE,
          outlineWidth: 2
        },
        label: {
          text: target.name,
          font: '14pt sans-serif',
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          pixelOffset: new Cesium.Cartesian2(0, -15)
        },
        description: target.description
      })
    }
  }
}

const loadGroundStations = async () => {
  const stations = JSON.parse(localStorage.getItem('groundStations') || '[]')
  
  for (const station of stations) {
    viewer.entities.add({
      name: station.name,
      position: Cesium.Cartesian3.fromDegrees(
        station.longitude,
        station.latitude,
        station.height
      ),
      point: {
        pixelSize: 15,
        color: Cesium.Color.GREEN,
        outlineColor: Cesium.Color.WHITE,
        outlineWidth: 2
      },
      label: {
        text: station.name,
        font: '14pt sans-serif',
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        outlineWidth: 2,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        pixelOffset: new Cesium.Cartesian2(0, -20)
      },
      description: `地面站: ${station.name}\n位置: ${station.longitude}, ${station.latitude}\n高度: ${station.height}m`
    })
  }
}

const loadPayloads = async () => {
  const payloads = JSON.parse(localStorage.getItem('payloads') || '[]')
  
  for (const payload of payloads) {
    const satellite = JSON.parse(localStorage.getItem('satellites') || '[]')
      .find(s => s.id === payload.satelliteId || s.name === payload.satelliteId)
    
    if (satellite) {
      viewer.entities.add({
        name: payload.name,
        position: Cesium.Cartesian3.fromDegrees(
          satellite.longitude || 116.4,
          satellite.latitude || 39.9,
          satellite.height || 1000000
        ),
        point: {
          pixelSize: 8,
          color: Cesium.Color.PURPLE,
          outlineColor: Cesium.Color.WHITE,
          outlineWidth: 1
        },
        label: {
          text: payload.name,
          font: '12pt sans-serif',
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          outlineWidth: 1,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          pixelOffset: new Cesium.Cartesian2(0, -10)
        },
        description: `载荷: ${payload.name}\n类型: ${payload.type}\n视场: ${payload.fovType}\n半锥角: ${payload.halfAngle}°`
      })
    }
  }
}

const loadCzmlData = async (czmlData) => {
  if (!viewer) return false
  
  try {
    let data = czmlData
    
    // 如果是字符串且是有效的CZML格式
    if (typeof czmlData === 'string') {
      // 尝试解析为JSON
      try {
        data = JSON.parse(czmlData)
      } catch {
        // 如果不是JSON，直接作为CZML字符串处理
        data = czmlData
      }
    }
    
    // 使用Cesium的CZML加载器
    const dataSource = await Cesium.CzmlDataSource.load(data)
    viewer.dataSources.add(dataSource)
    
    // 自动缩放到加载的数据
    viewer.zoomTo(dataSource)
    
    return true
  } catch (error) {
    console.error('加载CZML数据失败:', error)
    return false
  }
}

const initCesium = async () => {
  if (viewer) {
    viewer.destroy()
    viewer = null
  }
  
  if (!hasScene.value) return

  // 配置Cesium Ion访问凭证
  Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI4MTNlOWJkNy01NTU0LTQ3ZWQtYmM3Yi1mNGViODFhOGY3NzQiLCJpZCI6MjgwODczLCJpYXQiOjE3NDEwNzIwNTl9.v7K25kZiBHwarMikqFQEH-NROT27E4JjdsmpUULH4J0"

  // 初始化Cesium Viewer
  // 使用场景配置中的时间参数
  const startTime = sceneConfig.value.startTime
  const stopTime = sceneConfig.value.endTime
  
  viewer = new Cesium.Viewer('cesiumContainer', {
    // 将viewer实例保存到路由meta中
    infoBox: false,
    timeline: true,
    animation: true,
    shouldAnimate: true,
    clockViewModel: new Cesium.ClockViewModel(
      new Cesium.Clock({
        startTime: startTime,
        currentTime: startTime,
        stopTime: stopTime,
        clockRange: Cesium.ClockRange.LOOP_STOP,
        multiplier: sceneConfig.value.timeStep, // 使用配置的时间步长
        shouldAnimate: true
      })
    ),
    imageryProvider: new Cesium.IonImageryProvider({ assetId: 3 }) // Standard Bing Aerial with Labels
  })

  // 加载卫星和地面目标数据
  await Promise.all([
    loadSatellites(),
    loadPointTargets(),
    loadGroundStations(),
    loadPayloads(),
    loadAreaTargets()
  ])


  // 设置时间轴范围
  viewer.clock.startTime = startTime.clone()
  viewer.clock.stopTime = stopTime.clone()
  viewer.clock.currentTime = startTime.clone()
  viewer.timeline.zoomTo(startTime, stopTime)

  // 设置初始视角
  await viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(
      sceneConfig.value.longitude,
      sceneConfig.value.latitude,
      sceneConfig.value.height
    ),
    orientation: {
      heading: Cesium.Math.toRadians(0),
      pitch: Cesium.Math.toRadians(-90),
      roll: 0.0
    }
  })
}

import { useCesiumStore } from '@/store/modules/cesium'

const cesiumStore = useCesiumStore()

onMounted(() => {
  initCesium().then(() => {
    cesiumStore.setViewer({
      loadCzmlData,
      destroy: () => {
        if (viewer) {
          viewer.destroy()
          viewer = null
        }
      }
    })
  })
})

watch(hasScene, (newVal) => {
  if (newVal) {
    // 使用nextTick确保DOM更新完成
    nextTick(() => {
      initCesium()
    })
  } else if (viewer) {
    viewer.destroy()
    viewer = null
  }
})

onUnmounted(() => {
  if (viewer) {
    viewer.destroy()
  }
})
</script>

<style scoped>
.cesium-container {
  width: 100%;
  height: 100%;
}

.home-page {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  font-size: 24px;
}
</style>
